<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>首页</title>
    <link rel="stylesheet" href="./css/index.css">
    <script src="./js/promiseajax.js"></script>
    <script src="./js/cookie.js"></script>

</head>

<body>
    <div class="box top">
        <div class="title">
            <a href="./login.html">登录</a>
            <a href="./register.html">注册</a>
        </div>
        <a href="./list.html">列表页</a>
    </div>
    <div class="goods goodsheight">
        <ul>

        </ul>
    </div>
</body>
<script>
    var box = document.querySelector('.box')
    var title = document.querySelector('.title')
    var username = getCookie('username')
    if (username) {
        title.innerHTML = `
        欢迎<a href="usercenter.html">${username}<a/>登录!!
        <a href="javascript:;" onclick = loginout()>退出登录</a>
        `
    }
    function loginout() {
        removeCookie('username')
        title.innerHTML = `
        <a href="./login.html">登录</a>
        <a href="./register.html">注册</a>
        `
    }
    var goods = document.querySelector('.goods')
    var ul = goods.querySelector('ul')
    var flag = true
    var page = 1
    var pagesize = 8
    getGoods()
    function getGoods() {
        if (!flag) return
        flag = false
        request({
            url: `/api/goods/getAllGoods/${page}/${pagesize}`,
        }).then((res) => {

            // console.log(res);
            var html = ''
            var data = res.data.data
            console.log(data);
            if (data.length === 0) {
                return
            }
            data.forEach(goods => {
                html += `
                <li>
                    <a href="detail.html?id=${goods._id}" style="display: block;width: 100%; height: 100%;">
            <img src="${goods.img_big_logo}" alt="">
            <p>价格:${goods.price}</p>
            <p class="goodstitle">${goods.title}</p>
            </a>
            </li>
            `
            });
            ul.innerHTML += html
            flag = true
            page++
        })
    }
    //实现懒加载商品
    var goodsheight = document.querySelector('.goodsheight')
    var windowTop = document.querySelector('.top')
    window.onscroll = function () {
        var t = document.documentElement.scrollTop || document.body.scrollTop
        // 当卷去的距离 + 浏览器高度 > 当前文档的高度的时候(说明已经快到底了)
        if (t + innerHeight > goodsheight.offsetHeight + windowTop.offsetHeight - 200) {
            getGoods()
        }
    }
</script>

</html>